package cn.zzu.faceorgans;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.linchaolong.android.imagepicker.ImagePicker;
import cn.zzu.faceorgans.faceAPI.FaceLandmark;
import cn.zzu.faceorgans.utils.Base64My;

import java.io.IOException;
import java.net.URI;
import java.util.Map;

// 该活动用于实验直接在图片上做标记
public class TestActivity3 extends AppCompatActivity implements View.OnClickListener{

    private ImagePicker imagePicker = new ImagePicker();

    Map<String, Double> pointMap;

    Uri photouri;

    Button take_photo; //照相按钮

    Button paintImage;  //绘图按钮

    ImageView imageViewPhoto;    // 获得的相片

    float yuanwidth;
    float yuanheight;

    float nowheight;
    float noweight;

    public static final int TAKE_PHOTO = 1;
    private Uri imageURI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test3);


        take_photo = findViewById(R.id.take_photo);
        paintImage = findViewById(R.id.paint);
        imageViewPhoto = findViewById(R.id.image_view_photo);

        take_photo.setOnClickListener(this);
        paintImage.setOnClickListener(this);

        // 设置标题
        imagePicker.setTitle("设置头像");
        // 设置是否裁剪图片
        imagePicker.setCropImage(false);


    }


    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.take_photo:
                startChooser();
                break;
            case R.id.paint:
//                startPaint();
                paintEyeBrow();
        }
    }

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 0x11){
                pointMap = (Map<String, Double>) msg.obj;
                System.out.println("map:"+pointMap.size());
                for (String key: pointMap.keySet()){
                    System.out.println("map:"+pointMap.get(key));
                }
            }
        }
    };

    // 选择图片
    private void startChooser() {
        // 启动图片选择器
        imagePicker.startChooser(this, new ImagePicker.Callback() {
            // 选择图片回调
            @Override public void onPickImage(Uri imageUri) {

                photouri = imageUri;
                imageViewPhoto.setImageURI(imageUri);
                String imageBase = Base64My.imageToBase64(URI.create(imageUri.toString()).getPath());
                getFromBaidu(imageBase);

            }

            // 用户拒绝授权回调
            @Override public void onPermissionDenied(int requestCode, String[] permissions,
                                                     int[] grantResults) {

                Toast.makeText(TestActivity3.this, "必须授权", Toast.LENGTH_SHORT).show();
            }
        });
    }


    // 调用百度API获取关键点
    private void getFromBaidu(String imageBase64){
       MyThread myThread = new MyThread(imageBase64);
        myThread.start();
    }

    class MyThread extends Thread{
        private String imageBase;

        public MyThread(String imageBase){
            this.imageBase = imageBase;
        }

        @Override
        public void run() {
//            String result = FaceLandmark.faceLandmark(imageBase);

            Map<String, Double> doubleMap = FaceLandmark.faceLandmarkImportantPoint2(imageBase);
            Message message = new Message();
            message.what = 0x11;
            message.obj = doubleMap;
            handler.sendMessage(message);
        }
    }

    // 开始绘制穴位
    private void startPaint(){
        noweight = imageViewPhoto.getWidth();
        nowheight = imageViewPhoto.getHeight();
        // 计算缩放
        float percentWidth = noweight / yuanwidth;
        float percentHeight = nowheight / yuanheight;
        Log.d("sufang: ", percentWidth + "  "+percentHeight);

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(TestActivity3.this.getContentResolver(), photouri).copy(Bitmap.Config.ARGB_8888, true);
            Canvas canvasTemp = new Canvas(bitmap);
            canvasTemp.drawColor(Color.TRANSPARENT);
            Paint p = new Paint();
            p.setColor(Color.RED);
//            String familyName ="宋体";
//            Typeface font = Typeface.create(familyName,Typeface.BOLD);
//            p.setTypeface(font);
//            p.setTextSize(22);
//            canvasTemp.drawText("写字。。。",50,50,p);
//                canvasTemp.drawBitmap(bmp, 50, 50, p);//画图

            canvasTemp.drawCircle(140.65f, 142.34f, 2, p);
            Drawable drawable = new BitmapDrawable(bitmap);
            imageViewPhoto.setImageDrawable(drawable);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 绘制眼部穴位
    private void paintEyeBrow(){
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(TestActivity3.this.getContentResolver(), photouri).copy(Bitmap.Config.ARGB_8888, true);
            Canvas canvasTemp = new Canvas(bitmap);
            canvasTemp.drawColor(Color.TRANSPARENT);
            Paint p = new Paint();
            p.setAntiAlias(true);
            p.setColor(Color.RED);
            p.setStrokeWidth(5);


            // 眉毛:
            // 86 : 左攒竹穴
            float x86 = pointMap.get("86x").floatValue(); // 需要将Double转为float
            float y86 = pointMap.get("86y").floatValue();
            canvasTemp.drawCircle(x86, y86, 2, p);
            // 41 : 左鱼腰穴
            float x41 = pointMap.get("41x").floatValue();
            float y41 = pointMap.get("41y").floatValue();
            canvasTemp.drawCircle(x41, y41, 2, p);
            // 87 : 左丝竹穴
            float x87 = pointMap.get("87x").floatValue();
            float y87 = pointMap.get("87y").floatValue();
            canvasTemp.drawCircle(x87, y87, 2, p);
            // 85 : 右攒竹穴
            float x85 = pointMap.get("85x").floatValue();
            float y85 = pointMap.get("85y").floatValue();
            canvasTemp.drawCircle(x85, y85, 2, p);
            // 24 : 右鱼腰穴
            float x24 = pointMap.get("24x").floatValue();
            float y24 = pointMap.get("24y").floatValue();
            canvasTemp.drawCircle(x24, y24, 2, p);
            // 84 : 右丝竹穴
            float x84 = pointMap.get("84x").floatValue();
            float y84 = pointMap.get("84y").floatValue();
            canvasTemp.drawCircle(x84, y84, 2, p);

            float xend, yend;

            // 画直线
            p.setStyle(Paint.Style.STROKE);
            p.setColor(Color.BLUE);
            p.setStrokeWidth(2);
            // 86 : 左攒竹穴
            xend = x86 + 150;
            yend = y86 - 90;
            canvasTemp.drawLine(x86, y86, xend,yend, p);
            // 41
            canvasTemp.drawLine(x41, y41, x86+ 120,y86-30, p);
            // 87
            canvasTemp.drawLine(x87, y87, x86+ 120,y86 + 20, p);

            // 画矩形方框
            p.setStyle(Paint.Style.FILL);
            p.setColor(Color.parseColor("#fd9c32"));
            RectF rectF = new RectF();
            // 86 : 左攒竹穴
            rectF.set(xend-30, yend-20, xend + 30, yend);
            canvasTemp.drawRoundRect(rectF,5f, 3f,p);
            // 41
            rectF.set(x86 + 120, y86-40, x86+180, y86-20);
            canvasTemp.drawRoundRect(rectF,5f, 3f,p);
            // 87
            rectF.set(x86 + 120, y86 + 10, x86+180, y86+30);
            canvasTemp.drawRoundRect(rectF,5f, 3f,p);


            // 写穴位
            p.setStrokeWidth(0.5f);
            p.setTextSize(10);
            p.setColor(Color.WHITE);
            p.setTextAlign(Paint.Align.CENTER);
            p.setShader(null);
            // 86 : 左攒竹穴
            canvasTemp.drawText("左攒竹穴", xend, yend - 5, p);
            // 41
            canvasTemp.drawText("左鱼腰穴", x86+150, y86-25, p);
            // 87
            canvasTemp.drawText("左鱼腰穴", x86+150, y86+25, p);


            Drawable drawable = new BitmapDrawable(bitmap);
            imageViewPhoto.setImageDrawable(drawable);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 赋值
    private void fuzhiyuanlai(int width, int height){
        yuanwidth = width;
        yuanheight = height;

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        imagePicker.onActivityResult(this, requestCode, resultCode, data);
    }

    // 获取原始图片的宽和高

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        imagePicker.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }
}